import java.io.File;
import java.io.FileWriter;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Scheduler extends Setup {
	/* Globals that make up block path */
	static String DIR = "../predictions";
	static String ALG = "AUM";
	static String DAT = "val";
	static int K = 310;
	static String BLOCK_PATH;

	/* End of command line globals */
	static int BEGIN = 0;
	static int END = 1000990;
	static int THREADS = 4;

	public static void main(String[] args) {
		go();
	}

	static void go() {
		makeBlockPath();
		makeFolder();
		setUserBPath();
		writeLastRunSettings();
		setup();
		execute();
	}

	static void makeBlockPath() {
		BLOCK_PATH = DIR + "/" + ALG + "/" + DAT + "/" + K + "/";
	}

	static void makeFolder() {
		File folder = new File(BLOCK_PATH);
		if (!folder.exists()) {
			folder.mkdirs();
		}
	}

	static void writeLastRunSettings() {
		File file = new File(DIR + "lastRunSettings.txt");
		FileWriter fw;
		try {
			fw = new FileWriter(file);
			fw.write(BLOCK_PATH + "\n");
			fw.write(THREADS);
			fw.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	static void setUserBPath() {
		if (DAT.contains("val")) {
			Setup.FILE_PATH_USER_B = "../track1/validationIdx1.txt" + ".ser";
		} else {
			Setup.FILE_PATH_USER_B = "../track1/testIdx1.txt" + ".ser";
		}
	}

	static void execute() {
		ExecutorService es = Executors.newFixedThreadPool(THREADS);
		for (int start = BEGIN; start < END; start += K) {
			int stop = start + K;
			if (stop > END) {
				stop = END;
			}
			es.execute(alg(start, stop));
		}
		es.shutdown();
	}

	static Runnable alg(int start, int stop) {
		/* Algorithm User Mean */
		if (ALG.contains("AUM"))
			return new AUM(start, stop);
		/* Algorithm Item Mean */
		else if (ALG.contains("AIM"))
			return new AIM(start, stop);
		/* Algorithm User Similarity */
		else if (ALG.contains("AUS"))
			return new AUS(start, stop);
		/* Algorithm Item Similarity */
		else if (ALG.contains("AIS"))
			return new AIS(start, stop);
		/* You forgot to add your Algorithm ERROR! */
		else
			System.out.println("Forgot to add your Algorithm: " + ALG);
		return null;
	}
}